// 先不做mysql, 用json  json前后端数据交换的标准

const Koa = require('koa')
const router = require('koa-router')()
const app = new Koa()
const HomeData = require('./Data/HomeSwiper/HomeSwiper.json')
const ServerData = require('./Data/serverData/ServerData.json')
const TryData = require('./Data/TryCarData/TryCarData.json')
const FindData = require('./Data/FindData/FindData.json')
const cors = require('koa2-cors');
const Mock = require('mockjs');

// 解决跨域
app.use(cors({
    origin: function (ctx) { //设置允许来自指定域名请求
        // if (ctx.url === '/test') {
        return '*'; // 允许来自所有域名请求
        // }
        // return 'http://localhost:3000'; //只允许http://localhost:8080这个域名的请求
    },
    maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
})
)

// 反复添加Koa文件和json文件
router.get('/homedata', async (ctx) => {
    ctx.response.body = {
        success: true,
        data: HomeData
    }
})

router.get('/home/server', async (ctx) => {
    ctx.response.body = {
        success: true,
        data: ServerData
    }
})

router.get('/trycar', async (ctx) => {
    ctx.response.body = {
        success: true,
        data: TryData
    }
})

router.get('/finddata/:page', async (ctx) => {
    let limit = 10
    let { page } = ctx.params
    let { active } = FindData
    console.log(limit, page, active, '------------');
    let list2 = active.slice((page - 1) * limit, page * limit)
    ctx.response.body = {
        success: true,
        data: {
            newLists: list2,
        }
    }
})

router.get('/find/:id', async (ctx) => {
    // console.log(ctx.params, "=======");
    const { id } = ctx.params;
    if (!id) {
        ctx.response.body = {
            success: false,
            msg: "请求有误"
        }
        return
    }
    // to be continue serverice 取数据库数据

    ctx.response.body = {
        success: true,
        data: Mock.mock({
            id,
            title: '@ctitle(5, 10)',
            price: '@float(60,100)'
        })
    }
})

app
    .use(router.routes())
    .use(router.allowedMethods())

// 1. http服务
// 2. 简单路由模块
// 3. cors
// 4. 返回数据

app.listen(9999, () => {
    console.log('server is running 9999');
})